<!--
 * @页面名称:分类目录权限
 * @描述: 
 * @作者: 
 * @Date:
-->
<template>
  <div class="catalogManage">
    <!-- 按钮组 -->
    <!-- <div class="button-group">
      <el-button @click="save" type="primary">保存</el-button>
    </div> -->
    <el-row>
      <!-- <el-col :span="5" style="height: 100%">
        <ztree :setting="treeSetting.setting" :nodes="treeSetting.treeData" @onClick="onClick"></ztree>
      </el-col> -->
      <div class="left">
        <ztree :setting="treeSetting.setting" :nodes="treeSetting.treeData" @onClick="onClick"></ztree>
      </div>
      <!-- 分类目录右边树 -->
      <div v-if="treeSetting2.treeData.length" class="middle">
        <div style="padding-bottom: 2px; margin-top: 5px; font-size: 12px">分类目录:</div>
        <ztree
          style="height: calc(100vh - 55px); overflow-y: scroll"
          :setting="treeSetting2.setting"
          :nodes="treeSetting2.treeData"
          @onClick="onClick2"
          @onCreated="onCreated"
        ></ztree>
      </div>
      <!-- <el-col :span="15" style="height: 100%">
        <p style="font-size: 12px; margin: 0">按钮权限:</p>
        <div class="check-group">
          <el-checkbox style="margin-right: 10px" v-model="checkAllCheckBox" @change="onCheckBoxAllChange">全选</el-checkbox>
          <el-button style="margin-right: 10px" @click="applyAllChild">应用到子目录</el-button>
          <el-button @click="applyAll">应用到所有目录</el-button>
        </div>
        <div :style="{ borderBottom: '1px solid #E9E9E9' }"></div>
        <el-row :style="{ marginBottom: '8px' }">
          <el-col :span="8">
            <el-checkbox @change="changeAll" v-model="checkAll1" :indeterminate="isIndeterminate1">全选</el-checkbox>
          </el-col>
          <el-col :span="4">
            <el-checkbox @change="changeAllFulltext" v-model="checkAll2" :indeterminate="isIndeterminate2">全文全选</el-checkbox>
          </el-col>
          <el-col :span="4">
            <el-checkbox @change="changeAllReport" v-model="checkAll3" :indeterminate="isIndeterminate3">报表全选</el-checkbox>
          </el-col>
        </el-row>
        <el-row v-show="isShowCheckBox" style="height: calc(100% - 90px); overflow: auto">
          <el-col :span="8">
            <el-checkbox-group v-model="checkedButton" @change="handleChange">
              <el-checkbox :label="item" v-for="item in TopCheckedList1" :key="item">
                {{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </el-col>
          <el-col :span="4">
            <el-checkbox-group v-model="checkedFulltext" @change="handleChange4">
              <el-checkbox :label="item" v-for="item in TopCheckedList2" :key="item">
                {{ item }}
              </el-checkbox>
            </el-checkbox-group>
          </el-col>
          <el-col :span="4">
            <el-checkbox-group v-model="checkedReport" @change="handleChange5">
              <el-checkbox :label="item" v-for="item in TopCheckedList3" :key="item">
                {{ item.RM_FileName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-col>
        </el-row>
      </el-col> -->
      <div class="right">
        <div class="btn-permission">
          <span>按钮权限:</span>
          <div class="check-group">
            <el-checkbox style="margin-right: 20px" v-model="checkAllCheckBox" @change="onCheckBoxAllChange">全选</el-checkbox>
          </div>
        </div>
        <el-button @click="applyAllChild">应用到子目录</el-button>
        <el-button class="apply" @click="applyAll">应用到所有目录</el-button>
        <div class="line"></div>
        <!-- <el-row :style="{ marginBottom: '8px' }">
          <div class="all">
            <el-checkbox @change="changeAll" v-model="checkAll1" :indeterminate="isIndeterminate1">全选</el-checkbox>
          </div>
          <div class="text-all" :span="4">
            <el-checkbox @change="changeAllFulltext" v-model="checkAll2" :indeterminate="isIndeterminate2">全文全选</el-checkbox>
          </div>
          <div class="table-all">
            <el-checkbox @change="changeAllReport" v-model="checkAll3" :indeterminate="isIndeterminate3">报表全选</el-checkbox>
          </div>
        </el-row> -->
        <el-row v-show="isShowCheckBox" style="min-width: 440px; height: calc(100% - 150px)">
          <div class="group-left">
            <div class="all">
              <el-checkbox @change="changeAll" v-model="checkAll1" :indeterminate="isIndeterminate1">全选</el-checkbox>
            </div>
            <div class="group-wrapper">
              <el-checkbox-group v-model="checkedButton" @change="handleChange">
                <el-checkbox :label="item" v-for="item in TopCheckedList1" :key="item">
                  {{ item }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <div class="group-middle">
            <div class="text-all">
              <el-checkbox @change="changeAllFulltext" v-model="checkAll2" :indeterminate="isIndeterminate2"
                >全文全选</el-checkbox
              >
            </div>
            <div class="group-wrapper">
              <el-checkbox-group v-model="checkedFulltext" @change="handleChange4">
                <el-checkbox :label="item" v-for="item in TopCheckedList2" :key="item">
                  {{ item }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <div class="groups-right">
            <div class="table-all">
              <el-checkbox @change="changeAllReport" v-model="checkAll3" :indeterminate="isIndeterminate3">报表全选</el-checkbox>
            </div>
            <div class="group-wrapper">
              <el-checkbox-group v-model="checkedReport" @change="handleChange5">
                <el-checkbox :label="item" v-for="item in TopCheckedList3" :key="item">
                  {{ item.RM_FileName }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </el-row>
      </div>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from "vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import { getButtonList, getFulltextList } from "@/enums/dynamicButton";
import Ztree from "@/components/ztree/Ztree.vue";

const { proxy } = useCurrentInstance();
// 父级表格数据
const tabClickFromParent = ref();
// 全宗树点击保存节点
const FondsTreeObj = ref();
// 分类树节点保存状态
const catalogTreeNode = ref();
// 按钮状态是否显示
const isShowCheckBox = ref(false);
// 左边tree配置
const treeSetting = reactive({
  setting: {
    // ztree配置
    data: {
      simpleData: {
        enable: true,
        idKey: "ID",
        pIdKey: "FatherID"
      },
      key: {
        name: "Name"
      }
    },
    check: {
      enable: false
    },
    view: {
      showIcon: false
    }
  },
  treeData: [],
  treeNode: {}
});
// 中间分类目录数据
const treeSetting2 = reactive({
  setting: {
    // ztree配置
    data: {
      simpleData: {
        enable: true,
        idKey: "Catalog_ID",
        pIdKey: "Catalog_Father"
      },
      key: {
        checked: "IsCheck",
        name: "Catalog_Name"
      }
    },
    check: {
      enable: true
    },
    view: {
      showIcon: false
    }
  },
  treeData: [] as any,
  ztreeObj: {} as any
});
// 全选按钮状态
const checkAllCheckBox = ref(false);
// 案卷全选状态
const checkAll1 = ref(false);
const isIndeterminate1 = ref(true);
// 按钮数据
const TopCheckedList1 = ref([]);
// 按钮勾选数据
const checkedButton = ref<string[]>([]);
// 全文全选状态
const checkAll2 = ref(false);
const isIndeterminate2 = ref(true);
// 全文按钮数据
const TopCheckedList2 = ref(getFulltextList());
// 全文按钮勾选数据
const checkedFulltext = ref<string[]>([]);
// 报表全选状态
const checkAll3 = ref(false);
const isIndeterminate3 = ref(true);
// 报表按钮数据
const TopCheckedList3 = ref();
// 报表按钮勾选数据
const checkedReport = ref<string[]>([]);
// 获取全宗数据
const getCatalogData = (record: any) => {
  tabClickFromParent.value = record;
  proxy.$vueAxios.get("MasterPermission/GetRolePermissionFondsFM", { gid: record.G_ID }).then((res: any) => {
    const data = res.List.filter((v: any) => v.IsCheck === true);
    treeSetting.treeData = data;
  });
};
// 点击全宗获取分类树
const onClick = (treeNode: any) => {
  TopCheckedList1.value = getButtonList();
  TopCheckedList1.value.push("导入", "导出", "打印", "刷新", "全屏", "自定义列");
  isShowCheckBox.value = false;
  FondsTreeObj.value = treeNode;
  console.log(treeNode.Fonds_ID, treeNode.ID, treeNode.Archive_Status);

  if (treeNode.Type === "FMT") {
    proxy.$vueAxios
      .get("MasterPermission/GetRolePermissionCatalog", {
        gId: tabClickFromParent.value.G_ID,
        fmtId: treeNode.FMT_ID,
        fmId: treeNode.FM_ID,
        status: treeNode.Archive_Status
      })
      .then((res: any) => {
        console.log(res.List);
        res.List.forEach((item: any) => {
          item.Catalog_Name = item.Catalog_Name + "(" + item.Catalog_Code + ")";
        });
        treeSetting2.treeData = res.List;
        treeSetting2.treeData.forEach((item: any) => {
          if (item.PC_PermissionStr === "" || item.PC_PermissionStr === null) {
            item.PC_PermissionStr = JSON.stringify([[], [], []]);
          }
        });
      });
    getReportData();
  } else {
    proxy.$message.warning("请选择正确的子节点");
    treeSetting2.treeData = [];
  }
};
// 获取报表数据
const getReportData = () => {
  proxy.$vueAxios
    .post("Master_Base_ReportModule/GetConditional", {
      order: "RM_Index asc",
      dtoList: [{ fieldName: "FMT_ID", fieldValue: FondsTreeObj.value.FMT_ID }]
    })
    .then((res: any) => {
      if (res.Mark) {
        TopCheckedList3.value = res.List.filter((v: any) => v.RM_Enabled);
      }
    });
};
// 点击分类树获取按钮权限
const onClick2 = (treeNode: any) => {
  const statusObject = {
    Collect: ["数据接收", "数据退回", "撤销接收", "移交入库", "入库确认", "撤销入库", "退回整编", "数据开放", "取消开放"],
    Arrangement: ["数据提交", "数据撤回", "入库确认", "退回整编", "数据开放", "取消开放"],
    Storage: ["数据提交", "数据撤回", "数据接收", "数据退回", "撤销接收", "移交入库", "撤销入库"],
    Utilization: [
      "数据提交",
      "数据撤回",
      "数据接收",
      "数据退回",
      "撤销接收",
      "移交入库",
      "入库确认",
      "撤销入库",
      "退回整编",
      "数据开放",
      "取消开放"
    ]
  };
  const filterArr = statusObject[FondsTreeObj.value.Archive_Status];
  TopCheckedList1.value = TopCheckedList1.value.filter(element => !filterArr.includes(element));

  catalogTreeNode.value = treeNode;
  isShowCheckBox.value = true;
  checkedButton.value = JSON.parse(treeNode.PC_PermissionStr)[0];
  checkedFulltext.value = JSON.parse(treeNode.PC_PermissionStr)[1];
  checkedReport.value = TopCheckedList3.value.filter((v: any) => JSON.parse(treeNode.PC_PermissionStr)[2].includes(v.RM_ID));
  console.log(checkedButton.value, checkedFulltext.value, checkedReport.value);
};
// 分类目录树初始化事件
const onCreated = (ztreeObj: any) => {
  treeSetting2.ztreeObj = ztreeObj;
};
// 全选按钮勾选事件
const onCheckBoxAllChange = (val: any) => {
  if (isShowCheckBox.value) {
    checkAllCheckBox.value = val;
    if (val) {
      checkedButton.value = TopCheckedList1.value;
      checkedFulltext.value = TopCheckedList2.value;
      checkedReport.value = TopCheckedList3.value;

      catalogTreeNode.value.PC_PermissionStr = JSON.stringify([
        checkedButton.value,
        checkedFulltext.value,
        checkedReport.value.map((v: any) => v.RM_ID)
      ]);
      console.log(catalogTreeNode.value.PC_PermissionStr);
    } else {
      checkedButton.value = [];
      checkedFulltext.value = [];
      checkedReport.value = [];
      catalogTreeNode.value.PC_PermissionStr = JSON.stringify([checkedButton.value, checkedFulltext.value, checkedReport.value]);
    }
  }
};
// 全选
const changeAll = (val: any) => {
  const VerbArray = JSON.parse(catalogTreeNode.value.PC_PermissionStr);
  checkedButton.value = val ? TopCheckedList1.value : [];
  isIndeterminate1.value = false;
  VerbArray[0] = checkedButton.value;
  catalogTreeNode.value.PC_PermissionStr = JSON.stringify(VerbArray);
  getTreeIDAndUpdate(catalogTreeNode.value, catalogTreeNode.value.PC_PermissionStr);
};
// 按钮改变状态
const handleChange = (value: any[]) => {
  const VerbArray = JSON.parse(catalogTreeNode.value.PC_PermissionStr);
  VerbArray[0] = value;
  const checkedCount = value.length;
  checkAll1.value = checkedCount === TopCheckedList1.value.length;
  isIndeterminate1.value = checkedCount > 0 && checkedCount < TopCheckedList1.value.length;
  catalogTreeNode.value.PC_PermissionStr = JSON.stringify(VerbArray);
  getTreeIDAndUpdate(catalogTreeNode.value, catalogTreeNode.value.PC_PermissionStr);
};
// 全文全选
const changeAllFulltext = (val: any) => {
  const VerbArray = JSON.parse(catalogTreeNode.value.PC_PermissionStr);
  checkedFulltext.value = val ? TopCheckedList2.value : [];
  isIndeterminate2.value = false;
  VerbArray[1] = checkedFulltext.value;
  catalogTreeNode.value.PC_PermissionStr = JSON.stringify(VerbArray);
  getTreeIDAndUpdate(catalogTreeNode.value, catalogTreeNode.value.PC_PermissionStr);
};
// 全文按钮改变状态
const handleChange4 = (value: any[]) => {
  const VerbArray = JSON.parse(catalogTreeNode.value.PC_PermissionStr);
  VerbArray[1] = value;
  const checkedCount = value.length;
  checkAll2.value = checkedCount === TopCheckedList2.value.length;
  isIndeterminate2.value = checkedCount > 0 && checkedCount < TopCheckedList2.value.length;
  catalogTreeNode.value.PC_PermissionStr = JSON.stringify(VerbArray);
  getTreeIDAndUpdate(catalogTreeNode.value, catalogTreeNode.value.PC_PermissionStr);
};
// 报表全选
const changeAllReport = (val: any) => {
  const VerbArray = JSON.parse(catalogTreeNode.value.PC_PermissionStr);
  checkedReport.value = val ? TopCheckedList3.value : [];
  VerbArray[2] = checkedReport.value.map((v: any) => v.RM_ID);
  console.log(VerbArray[2]);
  isIndeterminate3.value = false;
  catalogTreeNode.value.PC_PermissionStr = JSON.stringify(VerbArray);
  getTreeIDAndUpdate(catalogTreeNode.value, catalogTreeNode.value.PC_PermissionStr);
};
// 报表按钮改变状态
const handleChange5 = (value: any[]) => {
  const VerbArray = JSON.parse(catalogTreeNode.value.PC_PermissionStr);
  VerbArray[2] = value.map((v: any) => v.RM_ID);
  console.log(VerbArray[2]);
  const checkedCount = value.length;
  checkAll3.value = checkedCount === TopCheckedList3.value.length;
  isIndeterminate3.value = checkedCount > 0 && checkedCount < TopCheckedList3.value.length;
  catalogTreeNode.value.PC_PermissionStr = JSON.stringify(VerbArray);
  getTreeIDAndUpdate(catalogTreeNode.value, catalogTreeNode.value.PC_PermissionStr);
};
// 更新树节点
const getTreeIDAndUpdate = (oldtreeNode: { Catalog_ID: string }, arrList: string) => {
  if (arrList) {
    // 1、获取zTree对象
    if (treeSetting2.ztreeObj) {
      // 分类
      const treeNode = treeSetting2.ztreeObj.getNodeByParam("Catalog_ID", oldtreeNode.Catalog_ID);
      // 3、为要修改的节点赋值
      treeNode.PC_PermissionStr = Array.isArray(arrList) ? JSON.stringify(arrList) : arrList;
      // 4、修改该节点上的值
      treeSetting2.ztreeObj.updateNode(treeNode);
    }
  }
};
// 删除分类目录
const delCatalogTree = async () => {
  await proxy.$vueAxios.post(
    "Master_Base_Permission_Catalog/DeleteByMultipleConditions",
    [
      {
        fieldName: "FMT_ID",
        conditionalType: 6,
        fieldValue: FondsTreeObj.value.FMT_ID
      },
      {
        fieldName: "PC_Status",
        conditionalType: 0,
        fieldValue: FondsTreeObj.value.Archive_Status
      },
      {
        fieldName: "g_id",
        conditionalType: 0,
        fieldValue: tabClickFromParent.value.G_ID
      }
    ],
    { noLoading: true }
  );
};
// 新增分类目录
const addCatalogTree = async () => {
  const filterList = treeSetting2.treeData.filter((v: any) => v.IsCheck);
  const param = [] as any;
  filterList.forEach((item: any) => {
    param.push({
      pC_ID: proxy.$global.createID(),
      g_ID: tabClickFromParent.value.G_ID,
      fonds_ID: FondsTreeObj.value.Fonds_ID,
      fmT_ID: FondsTreeObj.value.FMT_ID,
      // pfmT_ID: 0,
      pC_Status: FondsTreeObj.value.Archive_Status,
      catalog_ID: item.Catalog_ID,
      pC_PermissionStr: item.PC_PermissionStr
    });
  });
  await proxy.$vueAxios.post("Master_Base_Permission_Catalog/AddList", param);
};
// 保存前先把改变数据反映到源数据
const observeChangeType = () => {
  if (treeSetting2.ztreeObj) {
    const treeNodes = treeSetting2.ztreeObj.getNodes();
    const simpleData = treeSetting2.ztreeObj.transformToArray(treeNodes);
    simpleData.forEach((item: any) => {
      const index = treeSetting2.treeData.findIndex((v: any) => v.Catalog_ID === item.Catalog_ID);
      if (index > -1) {
        treeSetting2.treeData[index].IsCheck = item.IsCheck;
        treeSetting2.treeData[index].PC_PermissionStr = item.PC_PermissionStr;
      }
    });
  }
};
// 保存
const save = async () => {
  observeChangeType();
  await delCatalogTree();
  await addCatalogTree();
  nextTick(() => {
    onClick2(catalogTreeNode.value);
  });
  isShowCheckBox.value = false;
};
// 应用到子目录
const applyAllChild = () => {
  if (treeSetting2.ztreeObj) {
    const simpleData = treeSetting2.ztreeObj.transformToArray(catalogTreeNode.value);
    simpleData.forEach((item: any) => {
      const index = treeSetting2.treeData.findIndex((v: any) => v.Catalog_ID === item.Catalog_ID);
      if (index > -1) {
        item.IsCheck = catalogTreeNode.value.IsCheck;
        item.PC_PermissionStr = catalogTreeNode.value.PC_PermissionStr;
        item.open = catalogTreeNode.value.open;
        treeSetting2.treeData[index].IsCheck = item.IsCheck;
        treeSetting2.treeData[index].PC_PermissionStr = item.PC_PermissionStr;
        treeSetting2.treeData[index].open = item.open;
      }
    });
  }
  proxy.$message.success("应用到子级目录成功!");
};
// 应用到所有目录
const applyAll = () => {
  if (treeSetting2.ztreeObj) {
    const treeNodes = treeSetting2.ztreeObj.getNodes();
    const simpleData = treeSetting2.ztreeObj.transformToArray(treeNodes);
    simpleData.forEach((item: any) => {
      const index = treeSetting2.treeData.findIndex((v: any) => v.Catalog_ID === item.Catalog_ID);
      if (index > -1) {
        item.IsCheck = catalogTreeNode.value.IsCheck;
        item.PC_PermissionStr = catalogTreeNode.value.PC_PermissionStr;
        item.open = catalogTreeNode.value.open;
        treeSetting2.treeData[index].IsCheck = item.IsCheck;
        treeSetting2.treeData[index].PC_PermissionStr = item.PC_PermissionStr;
        treeSetting2.treeData[index].open = item.open;
      }
    });
  }
  proxy.$message.success("应用到所有目录成功!");
};
// 将函数暴露给父组件
defineExpose({ getCatalogData, save });
</script>

<style>
.custom-drawer .el-drawer__body {
  overflow: hidden;
}
</style>
<style scoped lang="scss">
.catalogManage {
  height: calc(100% - 32px);
  .check-group {
    display: flex;
    align-items: center;
    margin-left: 10px;
  }
  .left {
    height: calc(100vh - 35px);
    margin-left: 10px;
    overflow-y: scroll;
  }
  .middle {
    margin-left: 10px;
  }
  .right {
    display: flex;
    flex-direction: column;
    margin-left: 10px;
    .btn-permission {
      display: flex;
      align-items: center;
      margin-top: -3px;
      font-size: 12px;
    }
    .apply {
      margin: 8px 0 0;
    }
    .line {
      height: 1px;
      margin: 10px 0;
      background-color: #e9e9e9;
    }
    .group-left,
    .group-middle,
    .groups-right {
      height: 100%;
    }
    .group-middle {
      margin: 0 6px;
    }
    .group-left {
      display: flex;
      flex-direction: column;
      .all {
        height: 32px;
      }
      .group-wrapper {
        height: 750px;
        overflow-y: scroll;
      }
      .el-checkbox-group {
        flex: 1;
        overflow-y: scroll;
      }
    }
  }
  .z-tree {
    padding-right: 6px;
    overflow: unset;
  }
  .el-checkbox-group {
    display: flex;
    flex-direction: column;
  }
}
</style>
